#include "startwindow.h"


StartWindow::StartWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::StartWindow)
{
  ui->setupUi(this);
  //初始化用户界面
  UserWin = new UserWindow;

  //点击了登陆按钮,判断用户身份和密码是否匹配
  //若匹配则释放登陆成功信号,不匹配则弹出警告窗口
  connect(ui->ButtonLog, &QPushButton::clicked, [=](){
    int userIndex = ui->IdBox->currentIndex();
    QString userName = ui->EditUserName->text();
    QString userPassword = ui->EditPassword->text();
    //debug用,打印用户名和密码

    if ( IdConfirm(userIndex, userName, userPassword) && userIndex>0 ) {
      UserWin->userIndex_ = userIndex; //将当前的身份信息传入User界面
      UserWin->Userinfo.buidid = Log.buildingid;
      UserWin->Userinfo.name = Log.name;
      emit LogSuccess();
    } else {
      //这里弹出错误警告窗口
      //后期可设置超过5次失败直接退出系统
      QMessageBox::critical(this,"错误", "身份或密码错误,请重试!");
    }
    });

  //登陆成功,清空输入值，隐藏本窗口,打开用户窗口
  connect(this, &StartWindow::LogSuccess, [=](){
    ui->EditUserName->clear();
    ui->EditPassword->clear();
    this->hide();
    UserWin->Log(Log);
  });

  //点击退出,关闭窗口
  connect(ui->ButtonExit, &QPushButton::clicked, this, &QMainWindow::close);

  //用户界面点击了退出,关闭userwindow,显示登陆界面
  connect(UserWin, &UserWindow::Logout, [=](){
    UserWin->hide();
    this->show();
  });

}

/* IdConfirm函数用来判断用户身份,密码等信息是否正确
 * 输入参数:IdBox的身份标识,输入的用户名,输入的用户密码
 * 输出参数:身份验证结果; 1:验证成功; 0:验证失败
 */
bool StartWindow::IdConfirm(int index, QString& name, QString& password) {
  bool idCorrect = 0;
  QString tablename;

  if (index == kSupevisor) { //主管登陆
    if (name == UserWin->SpAccount && password == UserWin->SpPassword)
      idCorrect = 1;
  } else if (index == kVolunt) {  //志愿者登陆
    if (name == UserWin->VolAccount && password == UserWin->VolPassword)
      idCorrect = 1;
  } else {
      if (index == kOwner)  //业主登录
        tablename = tableOwner;
      else if (index == kStaff) //物业员工登陆
        tablename = tableStaff;
      //这里调用数据库来判断身份和密码信息
      idCorrect = UserLog->Login(tablename, name, password, Log);
  }
  return idCorrect;
}

StartWindow::~StartWindow()
{
  delete ui;
}
